package com.twb.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.twb.core.base.entity.BaseLoginUser;
import com.twb.core.base.entity.TwbPageInfo;
import com.twb.core.base.service.impl.BaseService;
import com.twb.core.cache.redis.RedisUtil;
import com.twb.core.exception.ServiceException;
import com.twb.core.util.BeanUtils;
import com.twb.core.util.ExcelUtils;
import com.twb.core.util.TwbPageUtil;
import com.twb.system.entity.twbUserConfig.TwbUserConfig;
import com.twb.system.entity.twbUserConfig.dto.ExportExcelTwbUserConfigDto;
import com.twb.system.entity.twbUserConfig.dto.SearchTwbUserConfigDto;
import com.twb.system.entity.twbUserConfig.vo.SaveTwbUserConfigVo;
import com.twb.system.entity.twbUserConfig.vo.SearchTwbUserConfigVo;
import com.twb.system.entity.twbUserConfig.vo.UpdateTwbUserConfigByIdVo;
import com.twb.system.mapper.TwbUserConfigMapper;
import com.twb.system.service.ITwbUserConfigService;

/** 
 * @ClassName TwbUserConfigService 
 * @Description 用户配置管理service
 
 * @author DSY
 * @date 2022-01-27 10:13:37
 */ 
@Service("twbUserConfigService")
public class TwbUserConfigService extends BaseService<TwbUserConfigMapper,TwbUserConfig> implements ITwbUserConfigService {

	@Autowired
	TwbUserConfigMapper twbUserConfigMapper;

	@Autowired
	private RedisUtil redisUtil;
	
	/**
	 * @Title getSysConfig
	 * @Description 设置缓存前缀
	 * @return
	 * @author DSY
	 * @date 2021年12月25日 下午4:58:56
	 */
	private String getUserConfigKey() {
		String cachePrefix = this.twbConfigProperties.getCachePrefix();
		return cachePrefix+":userconfig";
	}

	@Override
	public boolean initRedisUserConfig() {
		
		return this.initRedisUserConfig(null);
	}
	
	@Override
	public boolean initRedisUserConfig(TwbUserConfig userconfig) {
		if(userconfig != null) {
			String key = getUserConfigKey()+":"+userconfig.getUserId()+"_"+userconfig.getConfigType();
			redisUtil.delete(key);
			redisUtil.set(key, userconfig.getConfigJson());
			return true;
		}
		//如果不是单个用户，则全部清除后再缓存
		redisUtil.delete(getUserConfigKey()+"*");
		TwbUserConfig record = new TwbUserConfig();
		record.setIsdel(0);
		List<TwbUserConfig> queryForList = this.list(record);
		for (TwbUserConfig twuserconfig : queryForList) {
			String key = getUserConfigKey()+":"+twuserconfig.getUserId()+"_"+twuserconfig.getConfigType();
			
			redisUtil.set(key, twuserconfig.getConfigJson());
		}
		return true;
	}
	
	@Override
	public TwbPageInfo<SearchTwbUserConfigDto> searchTwbUserConfig(SearchTwbUserConfigVo vo) {
		TwbPageUtil.startPage(vo);
		List<SearchTwbUserConfigDto> list = twbUserConfigMapper.searchTwbUserConfig(vo);
		return TwbPageUtil.of(list);
	}
	
	@Override
	public List<SearchTwbUserConfigDto> searchTwbUserConfigList(SearchTwbUserConfigVo vo) {
		List<SearchTwbUserConfigDto> list = twbUserConfigMapper.searchTwbUserConfig(vo);
		return list;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveTwbUserConfig(SaveTwbUserConfigVo vo) {
		
		TwbUserConfig checkVo = new TwbUserConfig();
		checkVo.setUserId(vo.getUserId());	//此处需要修改为需要校验重复的字段
		checkVo.setConfigType(vo.getConfigType());
		checkVo.setIsdel(0);
		TwbUserConfig config = this.getOne(checkVo);
		if(config != null) {
			BeanUtils.copyNotNullProperties(vo, config);
			this.setUpdateInfo(config);
			boolean result = this.updateById(config);
			if(result) {
				initRedisUserConfig(config);
			}
			return result;
		}
	
		TwbUserConfig record = new TwbUserConfig();
		BeanUtils.copyNotNullProperties(vo, record);
		record.setId(this.getUUID());
		this.setCreateInfo(record);
		this.setUpdateInfo(record);
		boolean result = this.save(record);
		if(result) {
			initRedisUserConfig(record);
		}
		return result;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateTwbUserConfigById(UpdateTwbUserConfigByIdVo vo) {
		TwbUserConfig record = twbUserConfigMapper.selectById(vo.getId());
		if(null == record) {
			throw new ServiceException("数据不存在");
		}
		
		BeanUtils.copyNotNullProperties(vo, record);
		this.setUpdateInfo(record);
		boolean result = this.updateById(record);
		if(result) {
			initRedisUserConfig(record);
		}
		return result;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteTwbUserConfigById(String id) {
		boolean result = this.removeById(id);
		return result;
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteTwbUserConfigByIds(String ids) {
		return this.removeByIds(Arrays.asList(ids.split(",")));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int logicBatchDeleteTwbUserConfigByIds(String ids) {
		List<String> list = new ArrayList<String>();
		Collections.addAll(list, ids.split(","));
		return twbUserConfigMapper.logicBatchDeleteByIds(list);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void exportExcel(SearchTwbUserConfigVo vo, HttpServletResponse response) throws Exception {
		List<ExportExcelTwbUserConfigDto> list = twbUserConfigMapper.searchExportTwbUserConfig(vo);
		ExcelUtils.exportExcel("用户配置管理", list, ExportExcelTwbUserConfigDto.class, response);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int importExcel(Map<String, String> map) {
		System.out.println(map.toString());
		return 0;
	}

	@Override
	public boolean deleteTwbUserConfigByUserIdAndType(String userId, String configType) {
		TwbUserConfig record = new TwbUserConfig();
		record.setUserId(userId);
		record.setConfigType(configType);
		boolean result = this.remove(record);
		if(result) {
			String key = getUserConfigKey()+":"+userId+"_"+configType;
			redisUtil.delete(key);
		}
		return result;
	}


	@Override
	public String getRedisUserConfig(String userId, String configType) {
		String key = getUserConfigKey()+":"+userId+"_"+configType;
		String configJson = redisUtil.get(key);
		if(StringUtils.isBlank(configJson)) {
			TwbUserConfig record = new TwbUserConfig();
			record.setIsdel(0);
			record.setConfigType(configType);
			record.setUserId(userId);
			TwbUserConfig twbUserConfig = this.getOne(record );
			if(twbUserConfig != null) {
				configJson = twbUserConfig.getConfigJson();
				redisUtil.set(key, twbUserConfig.getConfigJson());
			}
		}
		return configJson;
	}


	@Override
	public Map<String, String> getRedisLoginUserConfig() {
		BaseLoginUser loginUser = this.getLoginUser();
		if(loginUser != null) {
			Map<String, String> map = new HashMap<>();
			String userId = loginUser.getId();
			String columnConfig = this.getRedisUserConfig(userId, "1");
			if(StringUtils.isNotBlank(columnConfig)) {
				map.put("columnConfig", columnConfig);
			}
			String systemConfig = this.getRedisUserConfig(userId, "2");
			if(StringUtils.isNotBlank(systemConfig)) {
				map.put("systemConfig", systemConfig);
			}
			return map;
		}
		return null;
	}
}
